<template>
<el-main>
    <el-button type="primary" size="mini" icon="el-icon-plus" circle @click="add"></el-button>
    <el-dialog :title="formTitle" :visible.sync="visible" center @close="resetForm('train')">
        <form-model ref="train"></form-model>
        <div slot="footer" class="dialog-footer">
            <el-button class="cancel" @click="resetForm('train')">取 消</el-button>
            <el-button class="confirm" type="primary" @click="submitForm">确 定</el-button>
        </div>
    </el-dialog>
    <el-table :data="tableData" size="mini">
        <el-table-column type="expand">
            <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                    <el-form-item label="序号">
                        <span>{{ props.row.id }}</span>
                    </el-form-item>
                    <el-form-item label="摘要">
                        <span>{{ props.row.title }}</span>
                    </el-form-item>
                    <el-form-item label="关联行程">
                        <span>{{ props.row.title }}</span>
                    </el-form-item>
                    <el-form-item label="连锁需求">
                        <span>{{ props.row.require }}</span>
                    </el-form-item>
                    <el-form-item label="总结">
                        <span>{{ props.row.summary }}</span>
                    </el-form-item>
                    <el-form-item label="反馈">
                        <span>{{ props.row.feedback }}</span>
                    </el-form-item>
                    <el-form-item label="影响">
                        <span>{{ props.row.effect }}</span>
                    </el-form-item>
                    <el-form-item label="关联PPT">
                        <el-button type="info" plain size="mini" @click="openFolder(props.row.ppt_path)">{{ props.row.ppt_path }}</el-button>
                    </el-form-item>
                </el-form>
            </template>
        </el-table-column>
        <el-table-column prop="id" label="序号" min-width="5%" :sortable="true">
        </el-table-column>
        <!--<el-table-column prop="subject" label="主题" min-width="9%" :sortable="true" align="center">
        </el-table-column>-->
        <el-table-column prop="area" label="区域" min-width="8%" :sortable="true" align="center">
        </el-table-column>
        <el-table-column prop="chain_shop" label="连锁" min-width="10%" :sortable="true">
        </el-table-column>
        <el-table-column prop="type" label="类型" min-width="16%" :formatter="formatType">
            <template align="left" slot="header" slot-scope="scope">
                <tr class="selectHeader">
                    <td style="border-bottom:0px">
                        <p style="float:left">类型</p>
                    </td>
                    <td style="border-bottom:0px">
                        <el-select v-model="selectedType" filterable placeholder="请选择" size="mini" style="margin-top:12px;margin-left:1px;padding-left:1px" @change="changeType">
                            <el-option v-for="item in trainTypes" :key="item.showValue" :label="item.label" :value="item.showValue">
                            </el-option>
                        </el-select>
                    </td>
                </tr>
            </template>
        </el-table-column>
        <el-table-column prop="kind" label="品种" min-width="8%" :formatter="formatKind">
        </el-table-column>
        <el-table-column prop="start_time" label="开始时间" min-width="14%" :sortable="true" align="center">
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" min-width="14%" :sortable="true" align="center">
        </el-table-column>
        <el-table-column prop="len" label="时长" min-width="8%" :sortable="true">
        </el-table-column>
        <el-table-column align="left" min-width="17%">
            <template slot="header" slot-scope="scope">
                <el-input v-model="searchText" type="text" size="mini" placeholder="关键字搜索" clearable auto-complete="off" @keyup.enter.native="searchFull()" />
            </template>
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" circle size="mini" @click="handleEdit(scope.$index, scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="handleDelete(scope.$index, scope.row)"></el-button>
            </template>
        </el-table-column>
    </el-table>
    <page ref="page" v-on:sizechange="pagesizeChange" v-on:pagechange="pageChange"></page>
</el-main>
</template>

<style>
.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}

.selectHeader div {
    padding-left: 1px !important;
}
</style>

<script>
import formModel from "../TrainPage/Model";
import page from "../HomePage/Page";
const {
    remote,
    shell
} = require("electron");
const db = remote.getGlobal("db_local");

export default {
    data() {
        return {
            visible: false,
            tableData: [],
            searchText: "",
            username: "严总",
            currentSql: "",
            currentPageSql: "",
            pagesize: 5,
            page: 1,
            hasCondition: false,
            formTitle: "",
            selectedKind: "",
            selectedType: "",
            typeSearch: false,
            textSearch: false,
            showKindSelect: false,
            modelData: {},
            kinds: [{
                    index: 0,
                    showValue: "疾病知识"
                },
                {
                    index: 1,
                    showValue: "A"
                },
                {
                    index: 2,
                    showValue: "C"
                },
                {
                    index: 3,
                    showValue: "D"
                },
                {
                    index: 4,
                    showValue: "E"
                },
                {
                    index: 5,
                    showValue: "I"
                },
                {
                    index: 6,
                    showValue: "J"
                },
                {
                    index: 7,
                    showValue: "K"
                },
                {
                    index: 8,
                    showValue: "JN"
                },
                {
                    index: 9,
                    showValue: "ZD"
                },
                {
                    index: 10,
                    showValue: "ZDH"
                },
                {
                    index: 11,
                    showValue: "SG"
                },
                {
                    index: 12,
                    showValue: "GA"
                }
            ],
            trainTypes: [{
                    showValue: 0,
                    label: "微信培训"
                },
                {
                    showValue: 1,
                    label: "视频培训"
                },
                {
                    showValue: 2,
                    label: "直播培训"
                },
                {
                    showValue: 3,
                    label: "店员培训"
                },
                {
                    showValue: 4,
                    label: "消费者教育"
                },
                {
                    showValue: 5,
                    label: "员工内训"
                }
            ]
        };
    },
    created() {},
    mounted() {
        this.currentSql = this.currentNoConditionPageSql;
        this.currentPageSql = this.currentNoConditionNumSql;
        this.refreshList();
    },
    computed: {
        currentNoConditionPageSql: function () {
            let typeSelect = this.typeSearch ? " type=" + this.selectedType: "";
            return (
                "select train.*,trip.title from train left outer join trip on  train.parent_id=trip.id" + (typeSelect == '' ? '' : ' where ' + typeSelect) + " order by id desc limit " +
                this.pagesize +
                " offset " +
                this.pagesize * (this.page - 1)
            );
        },
        currentNoConditionNumSql: function () {
            let typeSelect = this.typeSearch ? " type=" + this.selectedType : "";
            return "select count(*) as num from train" + (typeSelect == '' ? '' : ' where ' + typeSelect);
        },
        currentConditionPageSql: function () {
            let typeSelect = this.typeSearch ? " type=" + this.selectedType + " and " : "";
            return (
                'select train.*,trip.title from train left outer join trip on train.parent_id=trip.id where' + typeSelect + ' (subject like "%' +
                this.searchText +
                '%" or train.area like "%' +
                this.searchText +
                '%" or chain_shop like "%' +
                this.searchText +
                '%" or require like "%' +
                this.searchText +
                '%" or summary like "%' +
                this.searchText +
                '%" or feedback like "%' +
                this.searchText +
                '%" or effect like "%' +
                this.searchText +
                '%") order by train.id desc limit ' +
                this.pagesize +
                " offset " +
                (this.page - 1) * this.pagesize
            );
        },
        currentConditionNumSql: function () {
            let typeSelect = this.typeSearch ? " type=" + this.selectedType + " and " : "";
            return (
                'select count(*) as num from train where ' + typeSelect + ' (subject like "%' +
                this.searchText +
                '%" or area like "%' +
                this.searchText +
                '%" or chain_shop like "%' +
                this.searchText +
                '%" or require like "%' +
                this.searchText +
                '%" or summary like "%' +
                this.searchText +
                '%" or feedback like "%' +
                this.searchText +
                '%" or effect like "%' +
                this.searchText +
                '%")'
            );
        }
    },
    methods: {
        add: function () {
            this.formTitle = "新增培训";
            this.visible = true;
        },
        resetForm: function (name) {
            this.$nextTick(() => {
                this.$refs.train.train = {
                    kind: []
                };
                this.visible = false;
            });
        },
        submitForm: function () {
            let trainInfo = this.$refs.train.train;
            if (!trainInfo.timeInterval) {
                return;
            }
            if (trainInfo.parent == "") {
                this.$message.error("请先创建行程或关联已有行程");
                return;
            }
            let start = trainInfo.timeInterval[0];
            let end = trainInfo.timeInterval[1];
            let id = trainInfo.id;
            let sql;
            if (id > 0) {
                sql =
                    'update train set subject="' +
                    trainInfo.subject +
                    '",start_time="' +
                    start +
                    '",end_time="' +
                    end +
                    '",area="' +
                    trainInfo.area +
                    '",kind="' +
                    trainInfo.kind.join(",") +
                    '",chain_shop="' +
                    trainInfo.shop +
                    '",type=' +
                    trainInfo.type +
                    ',require="' +
                    trainInfo.require +
                    '",ppt_path="' +
                    trainInfo.ppt +
                    '",len=' +
                    trainInfo.len +
                    ',summary="' +
                    trainInfo.summary +
                    '",feedback="' +
                    trainInfo.fd +
                    '",effect="' +
                    trainInfo.effect +
                    '",parent_id=' +
                    trainInfo.parent +
                    " where id= " +
                    id;
            } else {
                sql =
                    'insert into train (subject,start_time,end_time,type,kind,area,chain_shop,require,ppt_path,len,summary,feedback,effect,parent_id) values ("' +
                    trainInfo.subject +
                    '","' +
                    start +
                    '","' +
                    end +
                    '",' +
                    trainInfo.type +
                    ',"' +
                    trainInfo.kind.join(",") +
                    '","' +
                    trainInfo.area +
                    '","' +
                    trainInfo.shop +
                    '","' +
                    trainInfo.require +
                    '","' +
                    trainInfo.ppt +
                    '",' +
                    trainInfo.len +
                    ',"' +
                    trainInfo.summary +
                    '","' +
                    trainInfo.fd +
                    '","' +
                    trainInfo.effect +
                    '",' +
                    trainInfo.parent +
                    ")";
            }
            console.log("tag", sql);
            db.run(sql, err => {
                if (err != null) {
                    console.log(err);
                } else {
                    this.resetForm();
                    let newTrain = JSON.parse(JSON.stringify(trainInfo));
                    newTrain.start_time = newTrain.timeInterval[0];
                    newTrain.end_time = newTrain.timeInterval[1];
                }
            });
            this.refreshList();
        },
        handleEdit: function (index, row) {
            let id = row.id;
            let sql_one = "select * from train where id=" + id;
            db.get(sql_one, (err, record) => {
                console.info("tag", record);
                if (err != null) {
                    console.log(err);
                } else {
                    this.formTitle = "编辑培训";
                    this.visible = true;
                    this.$nextTick(() => {
                        this.$refs.train.train = {
                            kind: []
                        };
                        this.$refs.train.train = {
                            id: record.id,
                            subject: record.subject,
                            timeInterval: [record.start_time, record.end_time],
                            area: record.area,
                            kind: record.kind.split(",").map(val => {
                                return parseInt(val);
                            }),
                            shop: record.chain_shop,
                            type: record.type,
                            require: record.require,
                            ppt: record.ppt_path,
                            len: record.len,
                            summary: record.summary,
                            fd: record.feedback,
                            effect: record.effect,
                            parent: record.parent_id
                        };
                    });
                }
            });
        },
        refreshList: function () {
            if (this.hasCondition) {
                this.currentSql = this.currentConditionPageSql;
                this.currentPageSql = this.currentConditionNumSql;
            } else {
                this.currentSql = this.currentNoConditionPageSql;
                this.currentPageSql = this.currentNoConditionNumSql;
            }
            console.info('tag', this.currentSql)
            db.all(this.currentSql, (err, rows) => {
                if (err == null) {
                    this.tableData = rows;
                    this.pageInit();
                } else {
                    console.log("db", err);
                }
            });
        },
        handleDelete: function (index, row) {
            let id = row.id;
            let sql = "delete from train where id=" + id;
            db.run(sql, err => {
                if (err != null) {
                    console.log("db", err);
                }
            });
            this.refreshList();
        },
        pagesizeChange: function (pageInfo) {
            this.pagesize = pageInfo.size;
            this.refreshList();
        },
        pageInit: function () {
            db.get(this.currentPageSql, (err, row) => {
                if (err != null) {
                    console.log("db", err);
                } else {
                    this.$refs.page.total = row.num;
                }
            });
        },
        pageChange: function (pageInfo) {
            console.log("tag", pageInfo);
            this.page = pageInfo.currentPage;
            this.refreshList();
        },
        searchFull: function () {
            this.hasCondition = true;
            this.textSearch = true;
            this.refreshList();
        },
        formatKind: function (row, column, cellValue) {
            let valueArr = cellValue.split(",");
            let newValueArr = this.kinds.filter(kin => {
                return valueArr.indexOf("" + kin.index) >= 0;
            });
            return newValueArr
                .map(ele => {
                    return ele.showValue;
                })
                .join(",");
        },
        formatType: function (row, column, cellValue) {
            for (const typeone in this.trainTypes) {
                if (this.trainTypes.hasOwnProperty(typeone)) {
                    const element = this.trainTypes[typeone];
                    if (element.showValue == cellValue) {
                        return element.label;
                    }
                }
            }
        },
        openFolder: function (fullPath) {
            if (fullPath.indexOf("http") == 0) {
                shell.openExternal(fullPath);
            } else {
                shell.showItemInFolder(fullPath);
            }
            shell.beep();
        },
        changeType: function () {
            this.typeSearch = true;
            this.refreshList();
        }
    },
    components: {
        formModel,
        page
    }
};
</script>
